<template>
  <MeModal ref="modalRef">
    <n-space item-style="display: flex;">
      <n-checkbox v-model:checked="defaultExpandAll" label="折叠/展开" />
      <n-checkbox label="全选/全不选" @update:checked="onSelectAll" />
      <n-checkbox v-model:checked="cascade" label="级联选择" />
    </n-space>
    <n-scrollbar style="height: 300px" mt-10>
      <n-tree
        block-line
        checkable
        check-on-click
        :data="menuTree"
        :cascade="cascade"
        :checked-keys="checkedKeys"
        key-field="id"
        label-field="name"
        :default-expand-all="defaultExpandAll"
        @update:checked-keys="onSelect"
      />
    </n-scrollbar>
  </MeModal>
</template>

<script setup>
import { MeModal } from '@/components'
import { useModal } from '@/composables'
import api from '../api'

const { menuTree } = defineProps(['menuTree'])

const [modalRef, okLoading] = useModal()

const id = ref(0)
const checkedKeys = ref([])
const cascade = ref(false)
const defaultExpandAll = ref(true)

function handleOpen(options = {}) {
  const { row = {}, ...rest } = options
  checkedKeys.value = []
  cascade.value = false
  defaultExpandAll.value = true
  id.value = row.id
  checkedKeys.value = row.menu_ids
  modalRef.value.open({ ...rest, onOk: onSave })
}

async function onSave() {
  okLoading.value = true
  try {
    const { message } = await api.updateRoleMenu({ role_id: id.value, menu_ids: checkedKeys.value })
    $message.success(message)
  }
  finally {
    okLoading.value = false
  }
}

function onSelect(keys) {
  checkedKeys.value = keys
}

function onSelectAll(checked) {
  if (checked) {
    checkedKeys.value = getIds(menuTree)
  }
  else {
    checkedKeys.value = []
  }
}

function getIds(arr) {
  let ids = []
  for (const item of arr) {
    ids.push(item.id)
    if (item.children) {
      ids = ids.concat(getIds(item.children))
    }
  }
  return ids
}

defineExpose({
  handleOpen,
})
</script>
